function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function showSuccess (title) {
  wx.showToast({
    title,
    icon: 'success',
    duration: 2000
  })
}

export function showFail (title) {
  wx.showToast({
    title,
    icon: 'none',
    duration: 2000
  })
}

export async function addBook (isbn) {
  await wx.request({
    url: 'https://douban.uieee.com/v2/book/isbn/' + isbn,
    header: {'content-type': 'json'},
    method: 'GET',
    dataType: 'json',
    success: (res) => {
      if (res.statusCode && res.statusCode >= 200 && res.statusCode < 400) {
        res = res.data
        formatBook(res, isbn)
      }
    },
    fail: err => console.error(err)
  })
}

export function formatBook (book, isbn) {
  wx.cloud.init()
  const data = {}

  data.isbn = isbn
  data.author = book.author.join('/')
  data.title = book.title
  data.image = book.images.small
  data.publisher = book.publisher
  data.catalog = book.catalog
  data.pubdate = book.pubdate
  data.rating = book.rating.average
  data.count = 0 // 初始化每本书访问量
  data.tags = book.tags.map(tag => {
    return tag.name + ' ' + tag.count
  })
  data.authorInfo = book.author_intro
  data.summary = book.summary
  data.price = book.price.match(/(\d+.?\d+)/)[0] + '元'

  wx.cloud.callFunction({
    name: 'books',
    data
  })
    .then(res => {
      if (checkOk(res.errMsg)) {
        showMod({title: '添加成功', content: data.title + '添加成功'})
      }
    })
    .catch(err => {
      showMod({title: '添加失败', content: '请重试'})
      console.error(err)
    })
}

export function checkOk (errMsg) {
  let reg = /(:ok)$/
  return reg.test(errMsg)
}

export function showMod ({title, content, success}) {
  wx.showModal({
    title,
    content,
    confirmText: '确定',
    showCancel: false,
    success
  })
}

export default {
  formatNumber,
  formatTime,
  showSuccess,
  showFail,
  showMod,
  addBook,
  checkOk
}
